package AWT_GameDemo;

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;

public class DrawingGame {
    Frame s = new Frame("DrawGame");
    //定义画图区域的宽高
private final int AreaWidth =500;
private final int AreaHeight =400;
//用菜单组件选择画笔
private PopupMenu ColorChoice = new PopupMenu();
private MenuItem Green = new MenuItem("绿色画笔");
private MenuItem Red = new MenuItem("红色画笔");
private MenuItem Blue = new MenuItem("蓝色画笔");
//定义变量记录鼠标拖动过程中上一次所处位置
    private int OLDX = -1;
    private int OLDY =  -1;
//画笔颜色变量
    private Color PenColor = Color.BLACK;

//位图对象
BufferedImage imga = new BufferedImage(AreaWidth,AreaHeight,BufferedImage.TYPE_INT_RGB);




//通过位图获取关联的Graphic对象
Graphics g =imga.getGraphics();




//创建画布组件
    private class  MyCanvas extends Canvas{
    @Override
    public void paint(Graphics g) {
        g.drawImage(imga,0,0,null);
    }
}
MyCanvas DA = new MyCanvas();




public void intt(){
//组装视图逻辑控制
    ActionListener act = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
        String acColor = e.getActionCommand();
        switch (acColor){
            case"红色画笔":
                PenColor=Color.RED;
                break;
            case"绿色画笔":
                PenColor=Color.GREEN;
                break;
            case"蓝色画笔":
                PenColor=Color.BLUE;
                break;

        }
        }
    };
    //注册监听
    Red.addActionListener(act);
    Green.addActionListener(act);
    Blue.addActionListener(act);
    //菜单内容添加入菜单
    ColorChoice.add(Green);
    ColorChoice.add(Red);
    ColorChoice.add(Blue);
    //菜单添加入画布
    DA.add(ColorChoice);

    //添加鼠标监听触发菜单
    DA.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent e) {
            boolean ispop=e.isPopupTrigger();
            if(ispop){
                ColorChoice.show(DA,e.getX(),e.getY());
            }
            //重置xy
            OLDY = -1;
            OLDX = -1;
        }
    });
//设置画布为白色
    g.setColor(Color.white);
    g.fillRect(0,0,AreaWidth,AreaHeight);
//监听画图动作
DA.addMouseMotionListener(new MouseMotionAdapter() {
    @Override
    public void mouseDragged(MouseEvent e) {
        if (OLDX>0 && OLDY>0) {
            g.setColor(PenColor);
            g.drawLine(OLDX, OLDY, e.getX(), e.getY());

        }
        //修正xy起点值
        OLDX =e.getX();
        OLDY =e.getY();
        //重新绘显示
        DA.repaint();
    }
});
DA.setPreferredSize(new Dimension(AreaWidth,AreaHeight));






    s.add(DA);
    s.pack();
    s.setVisible(true);
    s.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });
}

    public static void main(String[] args) {
DrawingGame op = new DrawingGame();
op.intt();
    }
}
